package com.enjoy.stack;

public class EnjoyMyStack<E> implements MyStack<E> {

    @SuppressWarnings("unchecked")
    private E[] elements = (E[]) new Object[1];

    private int n = 0;//初始的元素个数

    @SuppressWarnings("unchecked")
    public EnjoyMyStack(int cap) {
        this.elements = (E[]) new Object[cap];
    }

    @Override
    public void push(E item) {
        judgeSize();
        elements[n++] = item;

    }

    @Override
    public E pop() {
        if (isEmpty()) {
            return null;
        }
        E item = elements[--n];
        elements[n] = null;
        return item;
    }

    @Override
    public int size() {
        return n;
    }

    @Override
    public boolean isEmpty() {
        return n == 0;
    }

    public void resize(int size) {
        @SuppressWarnings("unchecked")
        E[] temp = (E[]) new Object[size];
        for (int i = 0; i < n; i++) {
            temp[i] = elements[i];
        }
        elements = temp;
    }

    private void judgeSize() {
        if (elements.length <= n) {
            resize(2 * elements.length);
        } else if (n > 0 && n <= elements.length / 2) {
            resize(elements.length / 2);
        }
    }
}
